package com.qn.utils;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * 线程池工具类
 *
 * @author OLO
 */
@Slf4j
public class PoolSend {
    /**
     * 任务队列
     */
    BlockingQueue<Runnable> workQueue;
    /**
     * 线程池的接口
     */
    ExecutorService es;
    /**
     * 开始时间
     */
    Long startTime;

    /**
     * @param corePoolSize    初始线程
     * @param maximumPoolSize 最大线程
     */
    public PoolSend(Integer corePoolSize, Integer maximumPoolSize) {
        startTime = System.currentTimeMillis();
        //构造无界的任务队列，资源足够，理论可以支持无限个任务
        workQueue = new LinkedBlockingQueue<>();
        //2 core； 4 max
        es = new ThreadPoolExecutor(corePoolSize, maximumPoolSize,
                //30s keep alive
                3000, TimeUnit.SECONDS, workQueue,
                new ThreadPoolExecutor.CallerRunsPolicy());
    }

    public void send(Runnable task) {
        //将任务放入线程池
        es.execute(task);
    }

    /**
     * 关闭
     */
    public void close() {
        es.shutdown();
        //等待所有任务都执行结束
        while (true) {
            //所有的子线程都结束了
            if (es.isTerminated()) {
                log.info("共耗时:" + (System.currentTimeMillis() - startTime) / 1000.0 + "s");
                break;
            }
        }
    }

    /**
     * 关闭
     */
    public void closeThread() {
        es.shutdown();
        poolWait();
    }

    public void closeNow() {
        es.shutdownNow();
        poolWait();
    }

    public void poolWait() {
        while (true) {
            //等待所有任务都执行结束
            try {
                Thread.sleep(10000);
                log.info("等待子线程关闭");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //所有的子线程都结束了
            if (es.isTerminated()) {
                log.info("终于关闭了");
                log.info("共耗时:" + (System.currentTimeMillis() - startTime) / 1000 + "s");
                break;
            }
        }
    }

    public void poolWait2() {
        //等待所有任务都执行结束
        while (true) {
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //所有的子线程都结束了
            if (es.isTerminated()) {
                log.info("终于关闭了");
                log.info("共耗时:" + (System.currentTimeMillis() - startTime) / 1000 + "s");
                break;
            }
        }
    }

}
